//
//  SYHomeTableViewController.swift
//  YANAWeibo
//
//  Created by mac on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

//  重用标记
private let HomeTableViewCellIdentifier = "HomeTableViewCellIdentifier"

class SYHomeTableViewController: SYVistorTableViewController {
    
    //获取微博数据
    private lazy var statusListViewModel: SYStatusListViewModel = SYStatusListViewModel()
    
    /// 上啦加载视图
    private lazy var pullUpView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.backgroundColor = UIColor.redColor()
        return view
    }()
    
    /// 系统下拉刷新
//    private lazy var refreshCtr: UIRefreshControl = {
//        let Ctr = UIRefreshControl()
//        return Ctr
//    }()
    
    /// 第三方下拉刷新控件
    private lazy var thirdPullDownView: CZRefreshControl = {
        let ctr = CZRefreshControl()
        return ctr
    }()
    
    /// 自定义的下拉刷新控件
    private lazy var customRefresh: SYCustomRefreshControl = {
        let ctr = SYCustomRefreshControl()
        return ctr
    }()
    
    /// tip动画的控件
    private lazy var tipLabel: UILabel = {
        let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 12)
        label.textAlignment = .Center
        label.hidden = true
        return label
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if userLogin {
            setupTableView()
            loadStatus()
            // 设置tiplabel
            setupUI()
        
        }else{
            //未登录状态
            visitorView?.setVistorInfo(nil, imageName: nil)
        }
 
    }
    
    private func setupUI() {
        // 将tip添加到导航栏下面
        if let nav = self.navigationController {
            tipLabel.frame = CGRectMake(0, CGRectGetMaxY(nav.navigationBar.frame) - 35, ScreenWidth, 35)
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        }
        
    }
    
    private func setupTableView() {
        //注册cell
        tableView.registerClass(SYStatusTableViewCell.self, forCellReuseIdentifier: HomeTableViewCellIdentifier)
        //自动计算行号
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300
        //去掉分割线
        tableView.separatorStyle = .None
        // 设置上啦加载更多的视图
        tableView.tableFooterView = pullUpView
        //设置大小
        pullUpView.sizeToFit()
        
        // 第一种下拉刷新
//        refreshCtr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
////        self.refreshControl = refreshCtr
//        
//        tableView.addSubview(refreshCtr)
        
        // 第二种下拉刷新--第三方
        thirdPullDownView.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        tableView.addSubview(thirdPullDownView)
        
        // 自定义下拉刷新
//        customRefresh.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
//        tableView.addSubview(customRefresh)
        
        
    }
    
    @objc private func pullDownRefresh() {
        // 下拉刷新加载数据
        loadStatus()
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            
            // 结束刷新
            self.endRefreshing()
        })
    }
    
    
    
    private func loadStatus() {
        statusListViewModel.requestStatus(pullUpView.isAnimating()) { (isSuccess, message) -> () in
            
            if !self.pullUpView.isAnimating() {
                self.startAnimation(message)
            }
            // 结束动画
            self.endRefreshing()
            if isSuccess {
                self.tableView.reloadData()
            }
        }
        
    }
    
    private func endRefreshing() {
        // 关闭动画效果
        pullUpView.stopAnimating()
         // 结束刷新
//        refreshCtr.endRefreshing()
//        // 第三方结束刷新
        thirdPullDownView.endRefreshing()
        // 自定义下拉刷新
//        customRefresh.endRefreshing()
        
        
    }
    
    // 开始动画
    private func startAnimation(message: String) {
        
        // 防止执行动画再次进行
        if tipLabel.hidden == false {
            return
        }
        
        //赋值内容
        tipLabel.text = message
        tipLabel.hidden = false
        tipLabel.backgroundColor = RandomColor()
        
        // 动画
        UIView.animateWithDuration(1.5, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.frame.size.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1.5, animations: { () -> Void in
                    // 回到原始位置
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        //动画完成后隐藏
                        self.tipLabel.hidden = true
                })
        }
  
    }

    

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList?.count ?? 0
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellIdentifier, forIndexPath: indexPath) as! SYStatusTableViewCell
        cell.statusViewModel = statusListViewModel.statusList![indexPath.row]
        //出去选中颜色
        cell.selectionStyle = .None
        
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusListViewModel.statusList!.count - 1 && !pullUpView.isAnimating() {
            pullUpView.startAnimating()
            loadStatus()
        }
    }
    


}
